package com.boc.langxiang.ui.fragment.adm;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.boc.langxiang.Constant;
import com.boc.langxiang.R;
import com.boc.langxiang.contract.adm.AdmListContract;
import com.boc.langxiang.entity.bean.DesignerFilterBean;
import com.boc.langxiang.entity.events.LoginSuccessEvent;
import com.boc.langxiang.entity.request.AdmListRequest;
import com.boc.langxiang.entity.response.AdmEntity;
import com.boc.langxiang.entity.response.UserInfo;
import com.boc.langxiang.manager.UserInfoManager;
import com.boc.langxiang.presenter.adm.AdmListPresenter;
import com.boc.langxiang.ui.activity.adm.AdmSearchActivity;
import com.boc.langxiang.ui.activity.adm.AdmSimpleActivity;
import com.boc.langxiang.ui.activity.me.LeaveToFlowOutActivity;
import com.boc.langxiang.ui.adapter.adm.AdmAdapter;
import com.boc.langxiang.ui.dialog.DesignerFilterPop;
import com.boc.langxiang.ui.fragment.BaseFragment;
import com.boc.langxiang.util.T;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ADM主页
 */
public class AdmListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener, AdmListContract.View {


    @BindView(R.id.recylerview)
    RecyclerView mRecylerview;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeLayout;
    @BindView(R.id.iamge)
    ImageView iamge;
    @BindView(R.id.search_gp)
    RelativeLayout searchGp;
    @BindView(R.id.filter_icon)
    ImageView filterIcon;
    @BindView(R.id.tool_bar)
    RelativeLayout toolBar;
    @BindView(R.id.talk)
    ImageView mTalk;

    private AdmAdapter mAdapter;
    private AdmListContract.Presenter mPresenter;
    private int mPage = 1;
    private boolean mIsOnRefresh;
    private boolean mIsLoadmore;

    private DesignerFilterPop mDesignerFilterPop;

    private boolean isFilterOpen = false;
    private String mType;

    public static AdmListFragment newInstance() {
        AdmListFragment fragment = new AdmListFragment();
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_adm_list, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        talkVisibile();

        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW);
        mRecylerview.setHasFixedSize(true);
        mRecylerview.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        mRecylerview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsOnRefresh) {
                    return true;
                }
                return false;
            }
        });

        mDesignerFilterPop = new DesignerFilterPop(mContext, new DesignerFilterPop.OnDesignerFilterListener() {
            @Override
            public void onSelect(DesignerFilterBean filterBean) {
                if (!mType.equals(filterBean.getId())) {
                    mType = filterBean.getId();
                    onRefresh();
                }
            }
        });

        filterIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFilterOpen) {
                    isFilterOpen = false;
                    mDesignerFilterPop.dismissPop();
                } else {
                    isFilterOpen = true;
                    filterIcon.setImageResource(R.drawable.icon_close_filter);
                    mDesignerFilterPop.showPop(toolBar, new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            isFilterOpen = false;
                            filterIcon.setImageResource(R.drawable.icon_filter);
                        }
                    });
                }
            }
        });

        initAdapter();
        mPresenter = new AdmListPresenter(this);
        mType = AdmListRequest.ALL;
        mPresenter.admList(mPage, mType);
    }

    private void initAdapter() {
        mAdapter = new AdmAdapter(mContext, null);
        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.view_empty, (ViewGroup) mRecylerview.getParent(), false);
        mAdapter.setEmptyView(emptyView);
        mAdapter.openLoadAnimation();
        //控制itemview动画是否只在第一次显示
        mAdapter.isFirstOnly(false);
        mAdapter.setOnLoadMoreListener(this);
        mAdapter.openLoadMore(Constant.PAGE_SIZE, true);
        mRecylerview.setAdapter(mAdapter);
        mAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(mContext, AdmSimpleActivity.class);
                AdmEntity item = mAdapter.getItem(position);
                intent.putExtra("designerId", item.getId());
                startActivity(intent);
            }
        });
    }


    @Override
    public void onRefresh() {
        if (mIsOnRefresh || mIsLoadmore) {
            mSwipeLayout.setRefreshing(false);
            return;
        }
        mAdapter.openLoadMore(Constant.PAGE_SIZE, true);
        mIsOnRefresh = true;
        mPage = 1;
        mPresenter.admList(mPage, mType);
    }

    @Override
    public void onLoadMoreRequested() {
        if (mIsOnRefresh || mIsLoadmore) {
            return;
        }
        mRecylerview.post(new Runnable() {
            @Override
            public void run() {
                mIsLoadmore = true;
                mPage++;
                mPresenter.admList(mPage, mType);

            }
        });
    }

    @Override
    public void showLoading() {
        showProgressDialog();
    }

    @Override
    public void hideLoading() {
        hideDialog();
        mSwipeLayout.setRefreshing(false);
    }

    @Override
    public void onError(String code, String msg) {
        mIsLoadmore = false;
        mAdapter.notifyDataChangedAfterLoadMore(false);
        mIsOnRefresh = false;
        T.showShort(mContext, msg);
    }

    @Override
    public void admListSuccess(List<AdmEntity> res) {
        if (!isAdded()) {
            return;
        }
        if (mIsLoadmore) {
            mIsLoadmore = false;
            if (res == null) {
                mAdapter.notifyDataChangedAfterLoadMore(false);
                loadDone();
                return;
            }
            if (res.size() < Constant.PAGE_SIZE) {
                mAdapter.notifyDataChangedAfterLoadMore(res, false);
                loadDone();
            } else {
                mAdapter.notifyDataChangedAfterLoadMore(res, true);
            }

        } else {
            mIsOnRefresh = false;
            if (res == null) {
                return;
            }
            mAdapter.setNewData(res);
        }

    }

    private void loadDone() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_load_done, (ViewGroup) mRecylerview.getParent(), false);
        mAdapter.addFooterView(view);
    }

    @OnClick({R.id.talk, R.id.search_gp})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.talk:
                startActivity(new Intent(getActivity(), LeaveToFlowOutActivity.class));
                break;
            case R.id.search_gp:
                startActivity(new Intent(mContext, AdmSearchActivity.class));
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccessEvent(LoginSuccessEvent e) {
        talkVisibile();
    }

    private void talkVisibile() {
        mTalk.setVisibility(View.GONE);
        UserInfo userInfo = UserInfoManager.getInstance().getUserInfo();
        if (userInfo != null) {
            int status = userInfo.getStatus();
            if (status == 2 || status == 3) {
                mTalk.setVisibility(View.VISIBLE);
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}